package com.xudow.app.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.activeshare.edu.ucenter.common.messages.Sites;
import com.activeshare.edu.ucenter.common.messages.course.SitesInClassMessage;
import com.xudow.app.R;
import com.xudow.app.ui.task.SitesInClassTask;
import com.xudow.app.ui.task.SitesSaveTask;
import com.xudow.app.ui.user.OrdersActivity;

import org.w3c.dom.Text;

import java.util.HashMap;
import java.util.List;

public class SitesActivity extends BaseActivity implements AdapterView.OnItemClickListener,hadSiteIntf {
    private GridView sitgv;
    private TextView classroom,commit,select_sit_tv;
    String courseId="0",orderItemId="0";
    ListView rowcountLV;
    List<Sites> sitlist;
    SitesInClassMessage sitesmsg;
    GvAdapter myadapter;
    long sitid=0L;
    RelativeLayout commitly;
    View lastClickIndex=null;
    private boolean hassit=false;//该学生是否有选好座位
    private boolean fromcoursedetile=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sites);
        courseId=getIntent().getStringExtra("courseId");
        orderItemId=getIntent().getStringExtra("orderItemId");
        fromcoursedetile=getIntent().getBooleanExtra("fromcoursedetile",false);
        initView();
    }

    private void initView() {
        sitgv=(GridView)findViewById(R.id.sit_gv);
        classroom=(TextView)findViewById(R.id.class_room_tv);
        rowcountLV=(ListView)findViewById(R.id.rowcoun_lv);
        commit=(TextView)findViewById(R.id.select_commit_tv);
        select_sit_tv=(TextView)findViewById(R.id.select_sit_tv);
        commitly=(RelativeLayout)findViewById(R.id.commit_ly);
        rowcountLV.setDivider(null);
    }

    @Override
    protected void onStart() {
        super.onStart();
        initData();
    }

    private void initData() {
        HashMap<String,String> pramers=new HashMap<String, String>();
        if (null==orderItemId)
            orderItemId="0";
        Log.e( "initData: ","courseId:"+courseId+"orderitemid:"+orderItemId );
        pramers.put("courseId",courseId);
        pramers.put("orderItemId", orderItemId);
        SitesInClassTask task=new SitesInClassTask(getApplicationContext(),getsitesHandler);
        addTask(task);
        task.execute(pramers);
        showLodingDialog("正在加载");
    }

    private Handler  getsitesHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            hideLoadingDialog();
            if (msg.what == SitesInClassTask.SUCCESS) {
                getMyApp().makeToast("座位表获取成功");
                sitesmsg = (SitesInClassMessage) msg.obj;
                updataUI(sitesmsg.getSites(), sitesmsg.getRow(), sitesmsg.getCol());
            } else {
                String str=msg.getData().getString("errMessage");
                if (null==str)
                    str="座位表获取失败";
                getMyApp().makeToast(str);
                commitly.setVisibility(View.INVISIBLE);
                sitgv.setClickable(false);
            }
        }
    };

    private void updataUI(List<Sites> list,int row,int col) {
        String[] listdata=new String[row];
        for (int i=1;i<=row;i++){
            listdata[i-1]=i+"";}
        sitgv.setNumColumns(col);
        rowcountLV.setAdapter(new ArrayAdapter<String>(this, R.layout.item_row_count, listdata) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                convertView = View.inflate(getContext(), R.layout.item_row_count, null);
                TextView t = (TextView) convertView.findViewById(R.id.rowcoun_tv);
                t.setText(getItem(position));
                return convertView;
            }
        });
        myadapter=new GvAdapter(this,sitesmsg,this);
        sitgv.setAdapter(myadapter);
        Log.e( "initData: ","courseId:"+courseId+"orderitemid:"+(orderItemId.equals("0")) );

        if (orderItemId.equals("0")){//只查看课程座位情况
            commitly.setVisibility(View.INVISIBLE);
            sitgv.setClickable(false);
            return;
        }



    }



    @Override
    protected void onResume() {
        super.onResume();
        //该生已选座位情况
        if (!orderItemId.equals("0"))
             sitgv.setOnItemClickListener(this);
    }

    public void goBackClick(View view){finish();}
    public void OnCommitClick(View view){
        if (0==sitid) {
            getMyApp().makeToast("请选座后再确定");
            return;
        }
        if (myadapter.isSelected()){
            Sites site=myadapter.getSelectSite();
            int r=site.getSiterow()+1;
            int c=site.getSitecolumn()+1;
            getMyApp().makeToast("你已选中"+c+"-"+r+"座");
            return;
        }
        HashMap<String,String> pramers=new HashMap<String, String>();
        Log.e("commit: ", "siteIdId:" + sitid + "orderitemid:" + orderItemId);
        pramers.put("siteId", sitid + "");
        pramers.put("orderItemId",orderItemId);
        SitesSaveTask savetask=new SitesSaveTask(getApplicationContext(),savehandler);
        addTask(savetask);
        savetask.execute(pramers);
        showLodingDialog("正在加载");
    }

    /**
     * 选座提交Handler
     */
    private Handler savehandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            hideLoadingDialog();
            if (msg.what==SitesSaveTask.SUCCESS){
                getMyApp().makeToast("选座成功");
                Intent intent=new Intent(getApplicationContext(), OrdersActivity.class);
                intent.putExtra("orderstate",1);
                startActivity(intent);
                finish();
            }else{
                if (null==msg.getData().get("errMessage"))
                    getMyApp().makeToast("哦豁,座位没选上");
                else
                    getMyApp().makeToast(msg.getData().get("errMessage").toString());
            }
        }
    };

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Sites site=null;
        if (lastClickIndex!=null){
           lastClickIndex.setBackgroundResource(R.mipmap.sit1);
            select_sit_tv.setText("暂无数据");
            sitid=0;
        }
        if (myadapter.isSelected()){
            return;
        }
        int c=(position)%sitesmsg.getCol();
        int r=(position)/sitesmsg.getCol();
        for (Sites s:sitesmsg.getSites()) {
            if (s.getSiterow()==r&&s.getSitecolumn()==c){
                site=s;
                Log.e("onItemClick: ",s.getSitecolumn()+"---"+s.getSiterow());
            }
        }
            if (site.getStatus()==null)
                return;
            if (site.getStatus()!=1)
                getMyApp().makeToast("该座已选");
            else if (site.getStatus()==1){
                View v=view.findViewById(R.id.sit_tv);
                v.setBackgroundResource(R.mipmap.sit3);

                 sitid=site.getId();
                 select_sit_tv.setText((c+1)+"-"+(r+1));
                lastClickIndex=v;
            }
    }

    @Override
    public void updatacallback() {
        Log.e("updataUI: ", "myadapter.isSelected()--" + myadapter.isSelected());
        if (myadapter.isSelected()){
            Sites s=myadapter.getSelectSite();
            select_sit_tv.setText((s.getSitecolumn()+1)+"-"+(s.getSiterow()+1));
            commit.setBackgroundColor(Color.GRAY);
            commit.setText("座位已选");
            commit.setClickable(false);
            sitid=s.getId();
        }
    }
}

class GvAdapter extends BaseAdapter{
    Context context;
    SitesInClassMessage data;
    Sites site;
    boolean selected=false;
    hadSiteIntf sa;
    public Sites getSelectSite(){return site;}
    public boolean isSelected(){
        return selected;
    }
    public GvAdapter(Context context,SitesInClassMessage data,hadSiteIntf sa){
        this.context=context;
        this.data=data;
        this.sa=sa;
    }
    public void setData(SitesInClassMessage data){
        this.data=data;
        notifyDataSetChanged();
    }
    @Override
    public int getCount() {
        if (null==data)
            return 0;
        return data.getCol()*data.getRow();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View v, ViewGroup parent) {
        if (v==null){
            v=View.inflate(context,R.layout.item_sit_gv,null);
            TextView sittv=(TextView)v.findViewById(R.id.sit_tv);
            v.setVisibility(View.INVISIBLE);
            int c=(position)%data.getCol()+1;
            int r=(position)/data.getCol()+1;
            sittv.setText(c + "-" + r);
            for (Sites sit:data.getSites()) {
                int row=sit.getSiterow()+1;
                int col=sit.getSitecolumn()+1;
                if (row==r&&col==c){
                    sittv.setTag(sit);
                    Integer status=sit.getStatus();
                    if (null==status) {

                        sittv.setBackgroundResource(R.mipmap.sit2);
                        v.setVisibility(View.VISIBLE);//不可用
                    }else if(status==-1){
                        //TODO 标记该学生已选座位
                        selected=true;
                        this.site=sit;
                        sa.updatacallback();//更新activity中的提交模块和已选中座位信息
                        Log.e( "getView: ","row"+row+"col"+col+selected);
                        sittv.setBackgroundResource(R.mipmap.sit3);//该生已选座位
                        v.setVisibility(View.VISIBLE);
                    }else if(status==1) {

                        sittv.setBackgroundResource(R.mipmap.sit1);//可选的空位
                        v.setVisibility(View.VISIBLE);
                    }else{
                        sittv.setBackgroundResource(R.mipmap.sit2);//已被占用
                        v.setVisibility(View.VISIBLE);
                    }
                }
            }

        }
        return v;
    }
}

interface hadSiteIntf{
    void updatacallback();
}